<template>
  <div class="register">
    <div class="content">
      <el-form
        label-position="left"
        label-width="80px"
        :model="registerForm"
        ref="registerFormRef"
        :rules="registerFormRules"
      >
        <el-alert
          title="请尽量在三分钟以内完成注册，谢谢配合"
          type="warning"
          center
          show-icon
          :closable="false"
        >
        </el-alert>
        <el-steps :active="active" finish-status="success">
          <el-step title="验证手机号"> </el-step>
          <el-step title="填写账号信息"> </el-step>
          <el-step title="注册成功"> </el-step>
        </el-steps>
        <!-- 验证手机号板块 -->
        <div class="tab_1" v-if="active === 0">
          <el-card>
            <el-row type="flex" justify="center" :gutter="20">
              <el-col :span="10">
                <el-form-item label="手机号" prop="phone">
                  <el-input
                    v-model="registerForm.phone"
                    placeholder="请输入手机号"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <!-- <el-button>获取验证码</el-button> -->
                <el-button :disabled="disabledFlag" @click="sendCaptcha">{{
                  registerFormText
                }}</el-button>
              </el-col>
            </el-row>
            <el-row type="flex" justify="center" :gutter="20">
              <el-col :span="10">
                <el-form-item label="验证码" prop="captcha">
                  <el-input
                    v-model="registerForm.captcha"
                    placeholder="请输入验证码"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4"> </el-col>
            </el-row>
            <div class="next">
              <el-button type="success" @click="tab1method">下一步</el-button>
            </div>
          </el-card>
        </div>
        <div class="tab_2" v-if="active === 1">
          <el-card>
            <el-row type="flex" justify="center" :gutter="20">
              <el-col :span="10">
                <el-form-item label="昵称" prop="nickname">
                  <el-input
                    v-model="registerForm.nickname"
                    placeholder="请输入昵称"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4"> </el-col>
            </el-row>
            <el-row type="flex" justify="center" :gutter="20">
              <el-col :span="10">
                <el-form-item label="密码" prop="password">
                  <el-input
                    v-model="registerForm.password"
                    placeholder="请输入密码"
                    type="password"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4"> </el-col>
            </el-row>
            <div class="next">
              <el-button type="success" @click="tab2method">下一步</el-button>
            </div>
          </el-card>
        </div>
        <div class="tab_3" v-if="active === 2">
          <el-card>
            <el-result
              icon="success"
              title="注册成功"
              subTitle="即将跳转到首页"
            >
            </el-result>
          </el-card>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import {
  validatePhoneRegister,
  getCaptcha,
  verifyCaptcha,
  registerUser,
} from "../../api/registerApi";
import { setLocalStorgeItem } from "../../utils/storage";
export default {
  name: "register",
  components: {},
  data() {
    var validatePhone = (rule, value, callback) => {
      // ^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$  验证手机号
      // 真 / 假
      let regPhone =
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      // let regPhone =
      //   /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/;
      if (!regPhone.test(value)) {
        callback(new Error("请输入正确的手机号格式"));
      } else {
        callback();
      }
    };
    var validatePhoneRegisterReg = async (rule, value, callback) => {
      let result = await validatePhoneRegister(value);
      if (result.exist === 1) {
        callback(new Error("此手机号已经被注册,请换一个手机号"));
      } else {
        callback();
      }
    };

    // 验证密码
    var validatorPassword = (rule, value, callback) => {
      if (/^(([a-zA-Z])+(\d)+)$/.test(value)) {
        callback();
      } else {
        callback(new Error("密码要以字母打头"));
      }
    };

    return {
      active: 0,
      disabledFlag: false,
      registerFormText: "获取验证码",
      registerForm: {
        captcha: "",
        phone: "",
        password: "",
        nickname: "",
      },
      registerFormRules: {
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            min: 11,
            max: 11,
            message: "请输入正确的手机号位数",
            trigger: "blur",
          },
          { validator: validatePhone, trigger: "blur" },
          { validator: validatePhoneRegisterReg, trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 8,
            max: 12,
            message: "密码请保证8-12位",
            trigger: "blur",
          },
          { validator: validatorPassword, trigger: "blur" },
        ],
        captcha: [
          { required: true, message: "请输入验证码", trigger: "blur" },
          {
            min: 4,
            max: 4,
            message: "请输入正确的验证码位数",
            trigger: "blur",
          },
        ],
        nickname: [
          { required: true, message: "请输入昵称", trigger: "blur" },
          {
            min: 4,
            max: 8,
            message: "昵称要求4-8位",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {},
  methods: {
    ...mapMutations("userStore", [
      "changeProfile",
      "changeCookie",
      "changeToken",
    ]),
    // 发送验证码   复制的 账户登录里面的
    async sendCaptcha() {
      try {
        let s = 60;
        let timer;
        let validatePhonePromise = await new Promise((resole, reject) => {
          this.$refs.registerFormRef.validateField("phone", (phoneError) => {
            // 手机号 验证出错的情况
            // console.log("验证返回的结果", phoneError);
            if (phoneError.length != 0) {
              this.$message({
                message: phoneError,
                type: "error",
              });
              reject(phoneError);
            } else {
              // 如果验证的结果要是真的，那就会 返回 空
              resole(phoneError);
            }
          });
        });
        // 验证手机号成功 ，进入 发送验证码环节
        let getCaptchaResult = await getCaptcha(this.registerForm.phone);
        if (getCaptchaResult.code === 200) {
          // 验证码发送成功~
          this.$message({
            message: `向${this.registerForm.phone} 账户 发送验证码成功`,
            type: "success",
          });
          this.disabledFlag = true;
          timer = setInterval(() => {
            if (s == 0) {
              clearInterval(timer);
              this.registerFormText = "获取验证码";
              this.disabledFlag = false;
              return;
            }
            this.registerFormText = `${s}s后重试`;
            s--;
          }, 1000);
        } else {
          // 验证码 发送失败
          this.$message({
            message: getCaptchaResult.message,
            type: "error",
          });

          throw new Error(getCaptchaResult.message);
        }
      } catch (error) {
        console.log(error, "catch捕获错误");
      }
    },
    // 第一步的 下一步按钮
    async tab1method() {
      try {
        // 验证 验证码是否正确
        // 如果validateField 第一个参数是一个数组，它是分开验证的
        const validateList = []; // 定义空数组
        let captchaFormValidate = await new Promise((resolve, reject) => {
          this.$refs.registerFormRef.validateField(
            ["phone", "captcha"],
            (ErrorInfo) => {
              validateList.push(ErrorInfo);
            }
          );
          if (validateList[0] == "" && validateList.length == 1) {
            console.log("正确");
            resolve(true);
          } else {
            this.$message({
              message: "请根据错误信息，完善账户信息",
              type: "error",
            });
            // reject(false);
            // throw new Error("sss");
            return;
          }
        });

        // 与后端接口，进行验证码的验证
        let verifyCaptchaResult = await verifyCaptcha({
          phone: this.registerForm.phone,
          captcha: this.registerForm.captcha,
        });

        if (captchaFormValidate && verifyCaptchaResult.code == 200) {
          this.active = 1;
        }
      } catch (error) {
        console.log("发现错误");
        console.log(error.response.data.message.length);

        this.$message({
          message: error.response.data.message,
          type: "error",
        });
      }
    },
    // 填写 昵称 和密码 页面 的 下一步按钮
    async tab2method() {
      // 验证 账号密码表单
      try {
        let zhuceValidate = await new Promise((resolve, reject) => {
          this.$refs.registerFormRef.validate((flag) => {
            if (flag) {
              // 真的， 验证成功
              resolve(true);
            } else {
              this.$message({
                message: "请根据错误信息，完善账户信息",
                type: "error",
              });
              reject(false);
            }
          });
        });
        if (zhuceValidate) {
          let zhuceResult = await registerUser(this.registerForm);
          if (zhuceResult.code === 200) {
            console.log(zhuceResult);
            //  this.$router.push();
            console.log(this.$route.query.path);
            setLocalStorgeItem("profile", zhuceResult.profile);
            // setLocalStorgeItem("cookie", verifyLoginResult.cookie);
            setLocalStorgeItem("token", zhuceResult.token);

            // 配合 vuex
            this.changeProfile(zhuceResult.profile);
            this.changeToken(zhuceResult.token);

            this.active = 2;
            setTimeout(() => {
              this.active = 3;
            }, 2000);
            setTimeout(() => {
              this.$router.push("/");
            }, 4000);
          }
        }
      } catch (error) {
        console.log("第二步错误");
        this.$message({
          message: error.response.data.message,
          type: "error",
        });
      }
    },
  },
  computed: {
    ...mapState({
      userStoreProfile: (state) => state.userStore.profile,
      userStoreCookie: (state) => state.userStore.cookie,
      userStoreToken: (state) => state.userStore.token,
    }),
  },
};
</script>

<style lang="less" scoped>
.register {
  background-color: #fbfcfe;
  height: calc(100vh - 377px - 90px);
  display: flex;
  justify-content: center;
  align-items: center;
  .content {
    height: 400px;
    width: 800px !important;
    /deep/ .el-alert {
      margin-bottom: 25px;
    }

    /deep/ .el-step__head.is-process {
      color: @globalColor;
      border-color: @globalColor;
    }
    /deep/ .el-step__title.is-process {
      color: @globalColor;
      font-weight: normal;
    }
    /deep/ .el-card {
      margin-top: 20px;
    }
    .next {
      display: flex;
      justify-content: center;
      align-items: center;
      /deep/ .el-button--success {
        background-color: @globalColor;
      }
    }
  }
}
</style>
